package com.example.xpvideo.intercept;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.example.xpvideo.entity.User;
import com.example.xpvideo.enums.ErrCodeEnum;
import com.example.xpvideo.tools.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthIntercept implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    private final Log log= LogFactory.get(this.getClass());

    /***
     * 返回错误信息
     */
    private void setReturn(HttpServletResponse response,
                           ErrCodeEnum errCodeEnum) throws IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            JSONObject res = new JSONObject();
            res.put("errno", errCodeEnum.getCode());
            res.put("errmsg", errCodeEnum.getMessage());
            out = response.getWriter();
            out.append(res.toString());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
        }
    }


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("token");
        String o = (String) redisUtil.get("xpvideo:admins:" + token);
        User object = JSON.parseObject(o, User.class);
        String requestURI = request.getRequestURI();
        if (ObjectUtils.isEmpty(object)) {
            setReturn(response, ErrCodeEnum.unknown_10004);
            log.info("未授权认证URI路径:{}",requestURI);
            return false;
        }

        //后面获取tokenInfo，主要只用到USERid
        request.setAttribute("tokenInfo", object);
        return true;
    }
}
